﻿var DOUBANKEY = '01f949b22c16cf1a05ebdd1684446d4e';

function GetKeyValue(data, key, value) {
    key = key || '@name';
    value = value || '$t';
    var re = new Object();
    for (var i = 0; i < data.length; i++) {
        var k = data[i][key];
        if (k) {
            if (k == 'aka' && data[i]['@lang'] == 'zh_CN') {
                re['akazh_CN'] = data[i][value];
            } else {
                if (!re[k]) re[k] = [];
                re[k].push(data[i][value])
            }
        }
    }
    return re;
}

function ChineseFromUTF8(input) {
    var ar = input.split('&#');
    var output = [];
    for (var i = 0; i < ar.length; i++) {
        var index = ar[i].indexOf(';');
        if (index < 1) {
            output.push(ar[i]);
        } else {
            output.push(String.fromCharCode(parseInt(ar[i].substring(0, index))));
            if (index < ar[i].length - 1) {
                output.push(ar[i].substring(index + 1));
            }
        }
    }
    return output.join('');
}

function LoadDoubanData(query) {
    var xhr = new XMLHttpRequest();
    var url = 'http://api.douban.com/movie/subjects?q=' + encodeURI(query) + '&apikey=' + DOUBANKEY + '&alt=json'
    xhr.open("GET", url, true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            OnDoubanDataLoaded(eval('(' + xhr.responseText + ')'));
        }
    };
    xhr.send();
}

function OnDoubanDataLoaded(re) {

    var table = document.createElement('table');
    var trs = [];
    var j = 0;
    for (var i = 0; i < re['entry'].length; i++) {
        var entry = re['entry'][i];
        var temp = GetMovieTRContent(entry, j);
        if (temp.length > 0) {
            j++;
            trs = trs.concat(temp);
        }
    }

    var main = document.getElementById('main');
    var noMatchesP = main.getElementsByTagName('p')[0];
    if (j > 0) {
        var a = document.createElement('p');
        a.innerHTML = '<b>Popular Titles</b> (Displaying ' + j + ' Results)';
        main.insertBefore(a, noMatchesP);

        table.innerHTML = trs.join('');
        main.insertBefore(table, noMatchesP);
        main.removeChild(noMatchesP);
    } else {
        noMatchesP.style['display'] = '';
    }
}

function GetMovieTRContent(entry, index) {
    var trs = [];
    var attribute = GetKeyValue(entry['db:attribute']);
    if (attribute['imdb'] && entry['title']) {
        var imdbLink = attribute['imdb'][0];
        var imdbId = imdbLink.split('/')[4];
        var links = GetKeyValue(entry['link'], '@rel', '@href');
        var imgsrc = 'http://img3.douban.com/pics/movie-default-small.gif';
        if (links['image']) {
            imgSrc = links['image'][0];
        }
        var year = '';
        if (attribute['pubdate']) {
            var pubdate = attribute['pubdate'][0];
            year = '(' + new Date(pubdate.match(/\d{1,4}-\d{1,2}-\d{1,2}/g)[0]).getFullYear() + ')';
        }
        var title = entry['title']['$t'];
        var akazh_CN = attribute['akazh_CN'];
        if (akazh_CN && akazh_CN != title) {
            title += '&nbsp/&nbsp<span style="font-size:12px;">' + attribute['akazh_CN'] + '</span>';
        }

        trs.push('<tr>');

        trs.push('<td valign="top"><a onclick="(new Image()).src=\'/rg/find-tiny-photo-1/title_popular/images/b.gif?link=/title/' + imdbId + '/\';" href="/title/' + imdbId + '/"><img width="60px" height="80px" border="0" src="' + imgSrc + '"></a>&nbsp;</td>');

        trs.push('<td valign="top" align="right"><img width="1" height="6" src="/images/b.gif"><br>' + (index + 1) + '.</td>');

        trs.push('<td valign="top"><img width="1" height="6" src="/images/b.gif"><br><a onclick="(new Image()).src=\'/rg/find-title-2/title_popular/images/b.gif?link=/title/' + imdbId + '/\';" href="/title/' + imdbId + '/">' + title + '</a> ' + year);

        if (attribute['cast']) {
            trs.push('<p style="width:500px;padding-top:5px">');
            trs.push(attribute['cast'].slice(0, 35).join('/'));
            if (attribute['cast'].length > 35) {
                trs.push('/...');
            }
            trs.push('</p>')
        }
        trs.push('</td>')
        trs.push('</tr>');
    }
    return trs;
}

function OnPageLoad() {
    var main = document.getElementById('main');

    if (main && main.innerHTML.indexOf('No Matches.') > -1) {
        var noMatchesP = main.getElementsByTagName('p')[0];
        noMatchesP.style['display'] = 'none';
        var s = window.location.search;
        var a = s.indexOf('q=');
        var b = s.indexOf('&', a);
        var q = '';
        if (b < 0) {
            q = s.substring(a + 2);
        } else {
            q = s.substring(a + 2, b);
        }
        var s = decodeURI(q);
        if (s.indexOf('%') > -1) { s = unescape(q); }
        q = ChineseFromUTF8(s);
        LoadDoubanData(q);
    }
}

OnPageLoad();
